<script setup lang='ts'>
import { ref, onMounted } from "vue"
import { useCounterStore } from '../stores/counter'
import { useRouter } from 'vue-router'
import CommentPage from "@/components/CommentPage.vue"
import AllCommentPage from "@/components/AllCommentPage.vue"
import { getNextBookComment } from "@/api/index"
import { getBookComment } from "@/api/index"
import { showSuccessToast } from "vant"
const $router = useRouter()
const store = useCounterStore()
const replyList = ref<any>([])
const replyUrl = ref<any>($router.currentRoute.value.query.url)

const getCOmmentTime = (time: any) => {

    let t = new Date(time);
    let y = t.getFullYear();
    let m: any = t.getMonth() + 1
    let d: any = t.getDate()
    m = m < 10 ? '0' + m : m;
    d = d < 10 ? '0' + d : d;

    return `${y}年${m}月${d}日`
}
const userInfo = ref<any>(null)
const currentComment = ref<any>([])
onMounted(async () => {

    if (localStorage.getItem('userInfo')) {
        userInfo.value = JSON.parse(`${localStorage.getItem('userInfo')}`)
    }

    if (localStorage.getItem('comment')) {
        currentComment.value = JSON.parse(`${localStorage.getItem('comment')}`)
    }

    let bookCommentRes = await getBookComment($router.currentRoute.value.query.source_uuid)
    store.getAllComment([...bookCommentRes.data.all.list])

    let myComment = currentComment.value.filter((o: any) => o.book == $router.currentRoute.value.query.source_uuid)

    myComment = myComment.map((o: any) => o.info)

    replyList.value = store.bookAllCommentList
    replyList.value = [...myComment, ...replyList.value]


})
const showAllCommentList = ref<any>([])

const toShowAllReply = (commentId: string) => {
    showAllCommentList.value = [...showAllCommentList.value, commentId]
}

//触底加载
const loading = ref<boolean>(false)
const finished = ref<boolean>(false)
const isLoading = ref<boolean>(false)

const onLoad = async () => {

    if (!isLoading.value && replyUrl.value) {

        isLoading.value = true;

        let res = await getNextBookComment(replyUrl.value)

        replyList.value = [...replyList.value, ...res.data?.all?.list]
        replyUrl.value = res.data.all.next;

        loading.value = false
        isLoading.value = false;
        if (!replyUrl.value || replyList?.value?.length >= res.data.all.totalcount) {
            finished.value = true;
        }
    } else {
        finished.value = true;
    }
}

const comment = ref<string>('')
//获取焦点时先判断是否有登录，没有就跳转登录
const toComment = () => {
    let querys = $router.currentRoute.value.query
    if (!userInfo.value) {
        $router.push({ path: '/login', query: { source_uuid: querys.source_uuid, url: querys.url } })
    }
}
//input的onChange事件，是输入框内容发生变化离开输入框时触发
const releaseComment = () => {
    let obj = {
        avatar: userInfo.value.avatar,
        nickName: userInfo.value.nickName,
        userLevel: '1',
        grade: 5,
        time: Date.now(),
        likes: '0',
        comment: comment.value
    }

    replyList.value = [obj, ...replyList.value]
    comment.value = ''

    showSuccessToast('发布成功！')

    localStorage.setItem('comment', JSON.stringify([{ book: $router.currentRoute.value.query.source_uuid, info: obj }, ...currentComment.value]))
}
</script>

<template>
    <div id="comment">
        <div class="comment-header">
            <img src="@/assets/imgs/返回1.png" alt="" @click="$router.back()">
            <span>评论({{ replyList.length }})</span>
            <span></span>
        </div>
        <div v-if="replyList.length == 0" class="comment-empty">
            <p>快来当第一个写评论的人吧</p>
            <button>写评论</button>
        </div>
        <div class="comment-list" v-if="replyList.length > 0">
            <van-list v-model:loading="loading" :finished="finished" :offset="1" finished-text="没有更多了"
                loading-text="数据加载中" error-text="加载失败" @load="onLoad">
                <ul class="list">
                    <li v-for="c, index in replyList" :key="index">
                        <div class="avator-msg">
                            <div class="avator-img">
                                <img v-lazy="(c.avatar) || (c.avatar ? c.avatar + '?imageView&thumbnail=240y336' : '') || ('https://easyreadfs.nosdn.127.net/RsyqfItTi1c4eJ3Nmm6a9A==/8796093023794550480?imageView&thumbnail=240y336')"
                                    alt="">
                            </div>
                            <div class="author-msg">
                                <div class="up">
                                    <span>{{ c.nickName }}</span>
                                    <span>LV.{{ c.userLevel }}</span>
                                </div>
                                <div class="down">
                                    <ul class="start-good">
                                        <li v-for="i, index in c.grade" :key="index">
                                            <img src="@/assets/imgs/评分1.png" alt="">
                                        </li>
                                    </ul>
                                    <ul class="start-bad">
                                        <li v-for="b, index in (5 - Math.ceil(c.grade))" :key="index">
                                            <img src="@/assets/imgs/评分2.png" alt="">
                                        </li>
                                    </ul>
                                    <span>{{ getCOmmentTime(c.time) }}</span>
                                </div>
                            </div>
                            <div class="thumb-up">
                                <span v-if="c.likes > 0">{{ c.likes }}</span>
                                <img src="@/assets/imgs/点赞1.png" alt="">
                            </div>
                        </div>
                        <div class="avator-comment">
                            <p>{{ c.comment }}</p>
                        </div>
                        <div class="comment-reply">
                            <ul class="list" v-if="!showAllCommentList.includes(c.commentId) && c.replyCount > 0">
                                <CommentPage v-for="item, index in c.replyList" :key="index" :comment="item" />
                            </ul>
                            <p @click="toShowAllReply(c.commentId)"
                                v-if="!showAllCommentList.includes(c.commentId) && c.replyCount > 2">展开剩余部分</p>
                            <AllCommentPage v-if="showAllCommentList.includes(c.commentId)" :url="c.replyUrl" />
                        </div>
                    </li>
                </ul>
            </van-list>
        </div>
        <div class="comment-input">
            <div class="input-container">
                <img src="@/assets/imgs/写评论1.png" alt="">
                <input type="text" placeholder="写长评当大师，接收众人膝盖~" @focus="toComment" v-model="comment"
                    @change="releaseComment">
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
#comment {
    // background-color: #fff !important;

    .comment-header {
        padding: 10rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #eee;
        height: 50rem;

        img {
            width: 25rem;
        }

        span {
            font-size: 17rem;
            color: #333;
        }
    }

    .comment-empty {
        width: 100%;
        height: calc(100vh - 90rem);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        p {
            color: #999;
            font-size: 13rem;
            margin-bottom: 10rem;
        }

        button {
            background-color: #fff;
            border: 1rem solid #fc1c1c;
            padding: 2rem 22rem;
            border-radius: 20rem;
            color: #fc1c1c;
        }
    }

    .comment-list {
        padding: 20rem 10rem 0;
        height: calc(100vh - 90rem);
        overflow: auto;

        ul.list {
            li {
                margin: 10rem 0 20rem;

                .avator-msg {
                    display: flex;
                    justify-content: space-between;

                    .avator-img {
                        width: 45rem;
                        height: 45rem;
                        border-radius: 50%;
                        overflow: hidden;

                        img {
                            width: 100%;
                            height: 100%;
                        }
                    }

                    .author-msg {
                        flex-grow: 1;
                        margin-left: 15rem;

                        .up {
                            span {
                                color: rgb(56, 168, 212);
                                font-size: 14rem;

                                &:last-child {
                                    font-size: 12rem;
                                    color: #fc1c1c;
                                    border: 1rem solid #fc1c1c;
                                    padding: 0 4rem;
                                    margin-left: 8rem;
                                }
                            }
                        }

                        .down {
                            display: flex;
                            justify-content: left;
                            align-items: center;

                            ul.start-good {
                                display: flex;
                                align-items: center;

                                li {
                                    margin-right: 3rem;

                                    img {
                                        width: 10rem;
                                        display: block;
                                    }
                                }
                            }

                            ul.start-bad {
                                display: flex;
                                align-items: center;

                                li {
                                    margin-left: 3rem;

                                    img {
                                        width: 10rem;
                                        height: 10rem;
                                        display: block;
                                    }
                                }
                            }

                            >span {
                                color: #666;
                                margin-left: 10rem;
                            }
                        }
                    }

                    .thumb-up {
                        display: flex;
                        justify-content: left;
                        align-items: flex-start;

                        span {
                            font-size: 14rem;
                            color: #666;
                        }

                        img {
                            width: 20rem;
                        }
                    }
                }

                .avator-comment {
                    margin-left: 60rem;
                }

                .comment-reply {
                    margin-left: 60rem;
                    background-color: rgba(175, 171, 171, 0.116);

                    ul.list {
                        li {
                            padding: 10rem 10rem 3rem;

                        }
                    }

                    p {
                        color: rgb(56, 168, 212);
                        // background-color: #fff;
                        text-align: center;
                    }
                }

            }
        }
    }

    .comment-input {
        width: 100%;
        height: 40rem;
        background-color: #ccc;
        display: flex;
        align-items: center;
        justify-content: center;

        .input-container {
            background-color: #fff;
            width: 95%;
            height: 30rem;
            display: flex;
            align-items: center;
            border-radius: 5rem;
            overflow: hidden;

            img {
                width: 16rem;
                height: 16rem;
                margin-left: 10rem;
                margin-right: 10rem;
            }

            input {
                flex-grow: 1;
                background-color: #fff;
                border: none;
                height: 100%;
                font-size: 12rem;
            }
        }
    }
}
</style>
